package com.ruoyi.energy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.energy.domain.*;
import com.ruoyi.energy.domain.vo.NyCableAccountVO;
import com.ruoyi.energy.mapper.NyCableAccountMapper;
import com.ruoyi.energy.mapper.NyTransMapper;
import com.ruoyi.energy.mapper.NyTransPartArrsMapper;
import com.ruoyi.energy.mapper.NyTransPartMapper;
import com.ruoyi.energy.service.INyCableAccountService;
import com.ruoyi.system.api.RemoteBmCodeService;
import com.ruoyi.system.api.domain.RemoteSysBmType;
import com.ruoyi.system.api.enums.SysBmCodeTypeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 电缆台账Service业务层处理
 *
 * @author cjie
 * @date 2021-09-25
 */
@Service
public class NyCableAccountServiceImpl implements INyCableAccountService {
    @Autowired
    private NyCableAccountMapper nyCableAccountMapper;

    @Autowired
    private NyTransMapper nyTransMapper;
    @Autowired
    private NyTransPartMapper nyTransPartMapper;
    @Autowired
    private NyTransPartArrsMapper nyTransPartArrsMapper;

    @Autowired
    private RemoteBmCodeService remoteBmCodeService;

    /**
     * 查询电缆台账
     *
     * @param id 电缆台账ID
     * @return 电缆台账
     */
    @Override
    public NyCableAccount selectNyCableAccountById(Long id) {
        return nyCableAccountMapper.selectNyCableAccountById(id);
    }

    /**
     * 查询电缆台账列表
     *
     * @param nyCableAccount 电缆台账
     * @return 电缆台账
     */
    @Override
    public List<NyCableAccount> selectNyCableAccountList(NyCableAccount nyCableAccount) {
        return nyCableAccountMapper.selectNyCableAccountList(nyCableAccount);
    }

    /**
     * 新增电缆台账
     *
     * @param nyCableAccount 电缆台账
     * @return 结果
     */
    @Override
    public int insertNyCableAccount(NyCableAccount nyCableAccount) {
        //nyCableAccount.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        nyCableAccount.setCreateTime(DateUtils.getNowDate());
        nyCableAccount.setCreateBy(SecurityUtils.getUsername());
        return nyCableAccountMapper.insertNyCableAccount(nyCableAccount);
    }

    /**
     * 修改电缆台账
     *
     * @param nyCableAccount 电缆台账
     * @return 结果
     */
    @Override
    public int updateNyCableAccount(NyCableAccount nyCableAccount) {
        nyCableAccount.setUpdateTime(DateUtils.getNowDate());
        nyCableAccount.setUpdateBy(SecurityUtils.getUsername());
        return nyCableAccountMapper.updateNyCableAccount(nyCableAccount);
    }

    /**
     * 批量删除电缆台账
     *
     * @param ids 需要删除的电缆台账ID
     * @return 结果
     */
    @Override
    public int deleteNyCableAccountByIds(Long[] ids) {
        return nyCableAccountMapper.deleteNyCableAccountByIds(ids);
    }

    /**
     * 删除电缆台账信息
     *
     * @param id 电缆台账ID
     * @return 结果
     */
    @Override
    public int deleteNyCableAccountById(Long id) {
        return nyCableAccountMapper.deleteNyCableAccountById(id);
    }

    @Override
    public String importData(List<NyCableAccountVO> nyCableVOList) {
        if (StringUtils.isNull(nyCableVOList) || nyCableVOList.size() == 0) {
            throw new CustomException("导入抄表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (NyCableAccountVO nyCableVO : nyCableVOList) {
            try {
                this.insertData(nyCableVO);
                successNum++;
                //successMsg.append("<br/>" + successNum + "、记录 " + nyCableVO.getRoomNum() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、记录 " + nyCableVO.getParkNum()+ " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private void insertData(NyCableAccountVO nyCableVO){
        //查询变压器编号，不存在 插入变压器数据；
//        BuiPark buiPark = buiParkMapper.selectBuiParkByParkNum(nyCableVO.getParkNum());
        NyTrans nyTrans = nyTransMapper.selectNyTransByName(nyCableVO.getTransName(),nyCableVO.getParkNum());
        if(StringUtils.isNull(nyTrans)){
            nyTrans = new NyTrans();
            RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(nyCableVO.getTransNum(), SysBmCodeTypeValue.DEVICE);
            nyTrans.setNum(bmType.getNowCode());
            nyTrans.setName(nyCableVO.getTransName());
            nyTrans.setParkNum(nyCableVO.getParkNum());
            //nyTrans.setStandard(nyCableVO.getStandard());
            nyTrans.setMakeDate(nyCableVO.getMakeDate());
            nyTrans.setFactory(nyCableVO.getFactory());
            nyTrans.setFactoryNum(nyCableVO.getFactoryNum());
            nyTrans.setWeight(nyCableVO.getWeight());
            nyTrans.setPreCheckTime(nyCableVO.getPreCheckTime());
            nyTrans.setNextCheckTime(nyCableVO.getNextCheckTime());
            nyTrans.setUseDate(nyCableVO.getUseDate());
            nyTrans.setApprovalLoad(nyCableVO.getApprovalLoad());
            nyTrans.setInstallPosition(nyCableVO.getInstallPosition());
            nyTrans.setCreateTime(DateUtils.getNowDate());
            nyTrans.setCreateBy(SecurityUtils.getUsername());
            nyTransMapper.insertNyTrans(nyTrans);
        }
        nyCableVO.setTransId(nyTrans.getId());
        //查询部件编号，不存在 插入部件编号;
        NyTransPart nyTransPart = nyTransPartMapper.selectNyTransPartByPartName(nyCableVO.getTransId(),nyCableVO.getPartName());
        if(StringUtils.isNull(nyTransPart)){
            nyTransPart = new NyTransPart();
            //RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(nyCableVO.getPartNum(), SysBmCodeTypeValue.DEVICE);
            //nyTransPart.setNum(bmType.getNowCode());
            nyTransPart.setTransId(nyTrans.getId());
            nyTransPart.setType(nyCableVO.getPartType());
            //nyTransPart.setModal(nyCableVO.getPartModal());
            nyTransPart.setName(nyCableVO.getPartName());
            nyTransPart.setCreateBy(SecurityUtils.getUsername());
            nyTransPart.setCreateTime(DateUtils.getNowDate());
            nyTransPartMapper.insertNyTransPart(nyTransPart);
        }
        nyCableVO.setPartId(nyTransPart.getId());
        //插入空开;
        NyTransPartArrs nyTransPartArrs = nyTransPartArrsMapper.selectNyTransPartArrsByPart(nyCableVO.getTransId(),nyCableVO.getPartId(),nyCableVO.getSwiftNum());
        if(StringUtils.isNull(nyTransPartArrs)){
            nyTransPartArrs = new NyTransPartArrs();
            nyTransPartArrs.setTransId(nyCableVO.getTransId());
            nyTransPartArrs.setPartId(nyCableVO.getPartId());
            nyTransPartArrs.setAirNum(nyCableVO.getSwiftNum());
            nyTransPartArrs.setModal(nyCableVO.getSwiftModel());
            //nyTransPartArrs.setDiameter(nyCableVO.getDiameter());
            //nyTransPartArrs.setAllowLoad(nyCableVO.getAllowLoad());
            //nyTransPartArrs.setStatus(nyCableVO.getStatus());
            nyTransPartArrs.setEn(nyCableVO.getEns());
            nyTransPartArrs.setEnAllow(nyCableVO.getEnAllows());
            nyTransPartArrs.setCreateBy(SecurityUtils.getUsername());
            nyTransPartArrs.setCreateTime(DateUtils.getNowDate());
            nyTransPartArrsMapper.insertNyTransPartArrs(nyTransPartArrs);
            this.insertNyEnteriseLoad(nyTransPartArrs);
        }
        nyCableVO.setSwiftId(nyTransPartArrs.getAttrId());

        //插入电缆
        NyCableAccount nyCableAccount = new NyCableAccount();
        BeanUtil.copyProperties(nyCableVO,nyCableAccount);
        //nyCableAccount.setSwiftId();
        nyCableAccount.setCreateTime(DateUtils.getNowDate());
        nyCableAccount.setCreateBy(SecurityUtils.getUsername());
        this.insertNyCableAccount(nyCableAccount);
    }

    private void insertNyEnteriseLoad(NyTransPartArrs nyTransPartArrs) {
        String ens = nyTransPartArrs.getEn();
        String enAllows = nyTransPartArrs.getEnAllow();
        if (StringUtils.isNotNull(ens) && StringUtils.isNotNull(enAllows) ){
            Long attrId = nyTransPartArrs.getAttrId();
            List<NyEnteriseLoad> list = new ArrayList<NyEnteriseLoad>();
            String[] res1 = ens.split("/");
            String[] res2 = enAllows.split("/");

            for(int i=0;i<res1.length;i++){
                NyEnteriseLoad nyEnteriseLoad= new NyEnteriseLoad();
                nyEnteriseLoad.setAttrId(attrId);
                nyEnteriseLoad.setEntepriseName(res1[i]);
                if(i<res2.length){
                    nyEnteriseLoad.setApprovalLoad(Integer.parseInt(res2[i]));
                }
                list.add(nyEnteriseLoad);
            }

            if (list.size() > 0) {
                nyTransPartArrsMapper.batchNyEnteriseLoad(list);
            }
        }

    }
}
